#include  "AdParseLogic.h"
#include "AdDao.h"
#include "stdio.h"
#include <glib.h>
#define LOCAL_PATH "/home/vm/CC_ads/meatdio"
#include "curlRequestUtil.h"

char* getResPath(AdResource* ar){
    int adId = ar->ad_id;
    char* path = ar->path;
    //http://47.109.65.208/images/20.png
    char* fileName = g_path_get_basename(path);
    char* formatStr = "%s/%d_%s";
    // /home/heron/ronghuanet_ads/media/1_20.png
    // /home/heron/ronghuanet_ads/media/1_44.mp4
    return g_strdup_printf(formatStr,LOCAL_PATH,adId,fileName);
}

int downloadAdsAndGenLocalAdListToSqlite(Ad* ads[],int size){
    int result=0;
    for (int i = 0; i < size; i++)
    {
        Ad* ad=ads[i];
        int adId=ad->id;
        // 根据广告ID去数据库中查询广告信息
        Ad *adFromDb = getAd(adId);
        // 如果数据库查询出的广告为空，说明这个广告是新的
        if(adFromDb == NULL)
        {
            // 如果这个广告是新的，那么qt进程就一定要更新播放列表
            result = 1;
            // 既然这个广告dou是不存在的，那么本地久一定要存入数据库
            saveAd(ad);
            // 广告信息处理完了以后，还要处理广告资源信息
            for(int j=0;j<3;j++)
            {
                AdResource *ar = ad->resources[j];
                if(ar != NULL)
                {
                    char* resPath = getResPath(ar);

                    int res = downloadRes(ar->path,resPath);
                    if(res == -1)
                    {
                        printf("文件下载失败\n");
                        continue;
                    }

                    // 修改ar.path=本地路径
                    ar->path = resPath;

                    // 存入数据库
                    saveAr(ar);
                }
            }
        }else{
            updateAd(ad);
            for(int j=0;j<3;j++)
            {
                AdResource *ar = ad->resources[j];
                if(ar == NULL)
                {
                    continue;
                }
                char* sign = ar->sign;
                // 获取本地文件的加密后的字符串，和sign做比较
                char* localPath = getResPath(ar);
                gboolean exists = g_file_test(localPath,G_FILE_TEST_EXISTS);
                if(!exists)
                {
                    result = 1;
                    downloadRes(ar->path,localPath);
                    ar->path = localPath;
                    updateAr(ar);
                }else{
                    //char* localFIleSign = getMd5(localPath);
                    char* localFileSign = "jfjjfjfjj";
                    if(!g_str_equal(sign,localFileSign))
                    {
                        result = 1;
                        downloadRes(ar->path,localPath);
                        ar->path = localPath;
                        updateAr(ar);
                    }else{
                        printf("当前媒体资源没有更新，不做处理!\n");
                    }
                }
            }
        }
    }
    return result;
}